package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/utils"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["banner"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/banner.html")))
	common.Templates["banner_edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/banner_edit.html")))
}

func ListBanner(w http.ResponseWriter, r *http.Request) {

	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}

	var page, _ = data.PageBanner(pageNo, pageSize)

	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	var qs = r.RequestURI

	index := strings.Index(r.RequestURI, "&pageNo=")
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
	}
	page.Url = qs

	common.Templates["banner"].Execute(w, page)
}

func AddBannerUIHandler(w http.ResponseWriter, r *http.Request) {

	common.Templates["banner_edit"].Execute(w, nil)
}

func GetBannerHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	c, err := data.GetBannerById(id)
	if err != nil {
		common.Templates["5xx"].Execute(w, err)
		return
	}
	common.Templates["banner_edit"].Execute(w, c)
}

func AddOrEditBannerHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	link := r.PostFormValue("link")
	priority, _ := strconv.Atoi(r.PostFormValue("priority"))

	var imgUrl = ""
	f, header, err := r.FormFile("imgUrl")
	// 用户上传了主图
	if err == nil && f != nil {
		uploadedPath, err := utils.Upload(f, header.Filename)
		if err != nil {
			common.Error.Printf("upload banner img url failed, filename:%s, err:%v", header.Filename, err)
		} else {
			imgUrl = uploadedPath
			// 更新操作
			if id > 0 {
				// 删除老的图片(如果有)
				kp, _ := data.GetBannerById(id)
				if kp != nil && len(kp.ImgUrl) > 0 {
					fns := strings.LastIndex(kp.ImgUrl, "/")
					if fns > -1 {
						utils.Delete(kp.ImgUrl[fns+1:])
					}
				}
			}
		}
	}
	b := model.Banner{Id: id, Link: link, Priority: int8(priority), ImgUrl: imgUrl}
	if id <= 0 {
		id, err = data.AddBanner(b)
	} else {
		id, err = data.UpdateBanner(b)
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/banner/list", http.StatusFound)
}

func UpdateBannerStatusHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	status, err := strconv.Atoi(r.FormValue("status"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.UpdateBannerStatus(status, id)

	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/banner/list", http.StatusFound)
}
